<template>
  <div>
    <van-field
      v-model="selectArea"
      is-link
      readonly
      label="地区"
      required
      input-align="right"
      placeholder="请选择"
      @click="show = true"
    />
    <van-popup v-model="show" round position="bottom">
      <van-cascader
        v-model="cascaderValue"
        title="请选择所在地区"
        :options="options"
        :field-names="fieldNames"
        @close="show = false"
        @finish="onFinish"
        value=""
      />
    </van-popup>
  </div>
</template>

<script>
// Vant区划选择器-目前不可回显 其他功能可用
import { get_all_area } from "@/api/user.js";
import { Cascader } from 'vant';
export default {
  name: "page1",
  components: {'van-cascader':Cascader},
  props: {
    fieldValue: {
      require: false,
    },
    cascaderValue: {
      require: false,
    },
  },
  data() {
    return {
      selectArea: "",
      fieldNames: {
        text: "name",
        value: "id",
        children: "children",
      },
      show: false,
      // 选项列表，children 代表子选项，支持多级嵌套
      options: [
        {
          name: "",
          id: "",
          children: [],
        },
      ],
    };
  },
  created() {
    this.getArea();
    this.selectArea = this.fieldValue;
  },
  methods: {
    getTreeData(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          // children若为空数组，则将children设为undefined
          data[i].children = undefined;
        } else {
          // children若不为空数组，则继续 递归调用 本方法
          this.getTreeData(data[i].children);
        }
      }
      return data;
    },
    getArea() {
      get_all_area({level:3}).then((res) => {
        if (res.succeed) {
          this.options = this.getTreeData(res.data);
        }
      });
    },
    onChange({ value, selectedOptions, tabIndex }) {},
    onFinish({ selectedOptions }) {
      this.show = false;
      this.selectArea = selectedOptions.map((option) => option.name).join("/");
      this.$emit("getCurrentArea", selectedOptions);
    },
  },
};
</script>
<style lang="less" scoped>
</style>